﻿using MaterialDesignThemes.Wpf;
using NoteBook_Product.Extensions;
using NoteBook_Product.Interface;
using NoteBook_Product.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System.Collections.ObjectModel;

namespace NoteBook_Product.ViewModels
{
    public class MainViewModel : BindableBase, IConfigureService
    {
        public MainViewModel(IRegionManager regionManager)
        {
            _regionManager = regionManager;
            MenuBars = new();
            NavigateCommand = new(Navigate);
            GoForwardCommand = new((bar) =>
            {
                if (regionNavigationJournal?.CanGoForward == true)
                    regionNavigationJournal?.GoForward();
            });

            GoBackCommand = new((bar) =>
            {
                if (regionNavigationJournal?.CanGoBack == true)
                    regionNavigationJournal?.GoBack();
            });
        }

        public ObservableCollection<MenuBar>? MenuBars { get; set; }

        public DelegateCommand<MenuBar> NavigateCommand { get; private set; }
        public DelegateCommand<MenuBar> GoBackCommand { get; private set; }
        public DelegateCommand<MenuBar> GoForwardCommand { get; private set; }

        public readonly IRegionManager _regionManager;

        public IRegionNavigationJournal regionNavigationJournal { get; private set; }

        private void Navigate(MenuBar bar)
        {
            if (string.IsNullOrEmpty(bar?.Namespace)) return;

            _regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(bar.Namespace, back =>
            {
                // 找到上下文导航日志
                regionNavigationJournal = back.Context.NavigationService.Journal;
            });
        }

        private void CreateMenuBar()
        {
            MenuBars?.Add(new("Home", "首页", "IndexView"));
            MenuBars?.Add(new("NotebookOutline", "待办事项", "ToDoView"));
            MenuBars?.Add(new("NotebookPlus", "备忘录", "MemoView"));
            MenuBars?.Add(new("Cog", "设置", "SettingView"));
        }

        public void Configure()
        {
            CreateMenuBar();
            _regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate("IndexView");
        }
    }
}
